package com.gexiaobao.pigeon.ui.fragment.mine.training

import android.os.Bundle
import android.text.TextUtils
import android.view.inputmethod.EditorInfo
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import com.bin.david.form.core.SmartTable
import com.bin.david.form.core.TableConfig
import com.bin.david.form.data.CellInfo
import com.bin.david.form.data.format.bg.BaseCellBackgroundFormat
import com.bin.david.form.data.style.FontStyle
import com.bin.david.form.data.style.LineStyle
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.TrainingResultResponse
import com.gexiaobao.pigeon.app.network.ListDataUiState
import com.gexiaobao.pigeon.databinding.FragmentTrainingResultBinding
import com.gexiaobao.pigeon.viewmodel.MyTrainingViewModel
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 18:15
 * @Describe    : 我的训放-训放结果
 */
class FragmentTrainingResult : BaseFragment<MyTrainingViewModel, FragmentTrainingResultBinding>() {

    lateinit var data: SmartTable<TrainingResultResponse.ResultList>

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        initSmartTable()

        mDatabind.swipeRefreshLayout.init {
            showLoading(getString(R.string.loading))
            mViewModel.getTrainingResult(mTrainingId.toString(), "")
        }

        eventViewModel.trainingResult.observeInFragment(this) {
            val listDataUiState = ListDataUiState(isSuccess = true, listData = it)
            setSmartTableData(listDataUiState)
        }

        eventViewModel.toRefreshList.observeInFragment(this) {
            if (it) {
                showLoading(getString(R.string.loading))
                mViewModel.getTrainingResult(mTrainingId.toString(), "")
            }
        }

        mDatabind.etSearch.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH ->
                    searchPigeon()

                else -> {}
            }
            false
        }

        mDatabind.etSearch.addTextChangedListener {
            if (it!!.isEmpty()) {
                showLoading(getString(R.string.loading))
                mViewModel.getTrainingResult(mTrainingId.toString(), "")
            }
        }
    }

    private fun searchPigeon() {
        hideSoftKeyboard(activity)
        when {
            mViewModel.searchName.get().isEmpty() -> showMessage(getString(R.string.enter_the_name_of_the_foster_carer_you_want_to_inquire_about))
            else -> {
                showLoading(getString(R.string.loading))
                mViewModel.getTrainingResult(mTrainingId.toString(), mViewModel.searchName.get())
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvSearch) {
            when (it) {
                mDatabind.tvSearch -> {
                    showLoading(getString(R.string.loading))
                    mViewModel.getTrainingResult(
                        mTrainingId.toString(),
                        mViewModel.searchName.get()
                    )
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        showLoading(getString(R.string.loading))
        mViewModel.getTrainingResult(mTrainingId.toString(), "")
    }

    private fun initSmartTable() {
        data = mDatabind.smartTable as SmartTable<TrainingResultResponse.ResultList>
        val fontStyle = context?.let { ContextCompat.getColor(it, R.color.black) }
            ?.let { FontStyle(context, 18, it) }
        val contentStyle = context?.let { ContextCompat.getColor(it, R.color.comm_text_gray) }
            ?.let { FontStyle(context, 16, it) }
        val lineStyle = LineStyle()
        lineStyle.color = context?.let { ContextCompat.getColor(it, R.color.dedede) }!!
        data.config.columnTitleStyle = fontStyle
        data.config.contentStyle = contentStyle
        data.config.setHorizontalPadding(20)
            .setVerticalPadding(40)
            .setSequenceHorizontalPadding(20)
            .setSequenceVerticalPadding(40)
            .setShowTableTitle(false) // 去除标题
            .setFixedFirstColumn(true) //第一行作废
            .setShowXSequence(false)
            .setShowYSequence(false)
            .isFixedYSequence = true
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.trainingResult.observe(viewLifecycleOwner) {
            if (mDatabind.swipeRefreshLayout.isRefreshing) {
                mDatabind.swipeRefreshLayout.isRefreshing = false
            }
            dismissLoading()
            if (!it.isEmpty) {
                setSmartTableData(it)
            }
        }
    }

    private fun setSmartTableData(it: ListDataUiState<TrainingResultResponse.ResultList>?) {
        val listData = ArrayList<TrainingResultResponse.ResultList>()
        if (it != null) {
            it.listData?.forEachIndexed { index, resultList ->
                listData.add(index, resultList)
                if (!TextUtils.isEmpty(resultList.ringId)) {
                    val split = resultList.ringId.split("-")
                    if (split.size == 3) {
                        resultList.ringId = "${split[0]}-${split[1]}-\n${split[2]}"
                    }
                }
                if (!TextUtils.isEmpty(resultList.homingTime)) {
                    resultList.homingTime = resultList.homingTime.replace(" ", "\n")
                }
                if (!TextUtils.isEmpty(resultList.startTime)) {
                    resultList.startTime = resultList.startTime.replace(" ", "\n")
                }
                resultList.rank = if (resultList.scanStatus == 0) 0 else index + 1

                resultList.scanStatusStr =
                    if (resultList.scanStatus == 0) getString(R.string.no_homing) else resultList.homingTime
            }
            data.setData(listData)

            data.config.contentCellBackgroundFormat =
                object : BaseCellBackgroundFormat<CellInfo<*>>() {
                    override fun getBackGroundColor(t: CellInfo<*>): Int {
                        return TableConfig.INVALID_COLOR
                    }

                    override fun getTextColor(t: CellInfo<*>): Int {
                        val bean = it.listData?.get(t.row)
                        return if ("寄养人" == t.column.columnName) {
                            ContextCompat.getColor(context!!, R.color.bg_light_bllue)
                        } else if (0 == bean!!.scanStatus && (t.col == 1 || t.col == 2)) {
                            ContextCompat.getColor(context!!, R.color.color_red)
                        } else {
                            super.getTextColor(t)
                        }
                    }
                }

            data.tableData?.setOnItemClickListener { column, value, t, _, _ ->
                if ("寄养人" == column.columnName) {
                    if (t != null) {
                        if (!TextUtils.isEmpty(t.toString())) {
                            mViewModel.searchName.set(value)
                            showLoading(getString(R.string.loading))
                            mViewModel.getTrainingResult(mTrainingId.toString(), value)
                        }
                    }
                }
            }
        }
    }

    companion object {
        private var mTrainingId: Int = 0
        fun newInstance(
            id: Int,
            result: ArrayList<TrainingResultResponse.ResultList>
        ): FragmentTrainingResult {
            mTrainingId = id

            val fragment = FragmentTrainingResult()
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }
    }
}